package hos.base.dialog;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import hos.base.activity.BaseActivity;
import hos.base.view.IFragmentActivityX;
import hos.thread.IThread;

public abstract class BaseAppCompatDialogFragment extends AppCompatDialogFragment implements IFragmentActivityX<BaseActivity>, IThread {

    private int gravity;

    public BaseAppCompatDialogFragment() {
    }

    public BaseAppCompatDialogFragment(int contentLayoutId) {
        super(contentLayoutId);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        return dialog;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Dialog dialog = getDialog();
        if (dialog != null) {
            //如果isCancelable()是false 则会屏蔽物理返回键
            dialog.setCancelable(isCancelable());
            //如果isCancelableOutside()为false 点击屏幕外Dialog不会消失；反之会消失
            dialog.setCanceledOnTouchOutside(isCancelableOutside());
            //如果isCancelable()设置的是false 会屏蔽物理返回键
            dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    return keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN && !isCancelable();
                }
            });
        }
        applyBackground(view);
        onViewShowed(view);
    }

    protected void applyBackground(View view) {
        int padding12 = DialogUtils.dp2px(12);
        int padding8 = DialogUtils.dp2px(8);
        if (gravity == Gravity.BOTTOM) {
            view.setBackground(DialogUtils.getGradientDrawableBottom());
        } else {
            view.setBackground(DialogUtils.getGradientDrawable());
        }
        view.setPadding(padding12, padding8, padding12, padding8);
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog == null) {
            return;
        }
        Window currentWindow = dialog.getWindow();
        if (currentWindow == null) {
            return;
        }
        currentWindow.setBackgroundDrawableResource(android.R.color.transparent);
        ViewGroup group = (ViewGroup) currentWindow.getDecorView();
        ViewGroup child = (ViewGroup) group.getChildAt(0);
        child.post(() -> {
            WindowManager.LayoutParams param = currentWindow.getAttributes();
            if (gravity == Gravity.BOTTOM) {
                param.width = WindowManager.LayoutParams.MATCH_PARENT;
            } else {
                param.width = (int) (0.8 * DialogUtils.getWindowWidth(currentWindow));
            }
            param.gravity = gravity;
            currentWindow.setGravity(gravity);
            currentWindow.setAttributes(param);
        });
    }

    public boolean isCancelableOutside() {
        return true;
    }

    public void show() {
        show(Gravity.CENTER);
    }

    public void show(int gravity) {
        this.gravity = gravity;
        show(getClass().getSimpleName());
    }

    public void show(final String tag) {
        postOnMain(new Runnable() {
            @Override
            public void run() {
                FragmentManager fm = activity().getSupportFragmentManager();
                Fragment prev = fm.findFragmentByTag(tag);
                if (prev != null) {
                    fm.beginTransaction().remove(prev);
                }
                BaseAppCompatDialogFragment.super.show(fm, tag);
            }
        });
    }

    public void showNow() {
        showNow(Gravity.CENTER);
    }

    public void showNow(int gravity) {
        this.gravity = gravity;
        showNow(getClass().getSimpleName());
    }

    public void showNow(@Nullable String tag) {
        postOnMain(new Runnable() {
            @Override
            public void run() {
                FragmentManager fm = activity().getSupportFragmentManager();
                Fragment prev = fm.findFragmentByTag(tag);
                if (prev != null) {
                    fm.beginTransaction().remove(prev);
                }
                BaseAppCompatDialogFragment.super.showNow(fm, tag);
            }
        });
    }

    @Override
    public void dismiss() {
        postOnMain(new Runnable() {
            @Override
            public void run() {
                BaseAppCompatDialogFragment.super.dismissAllowingStateLoss();
            }
        });
    }

}


